/**
 * 
 */
package neptune.web.server.security;

import it.robertobifulco.ias.PermissionHandler;
import it.robertobifulco.ias.UnauthorizedOperationException;
import it.robertobifulco.ias.principalmanager.Principal;
import neptune.manager.storage.ExperimentRepositoryException;
import neptune.web.client.model.DefaultRoles;
import neptune.web.server.ApplicationManager;
import neptune.web.server.InitializationException;
import neptune.web.server.operations.PauseNode;
import neptune.web.server.operations.RebootNode;
import neptune.web.server.operations.SaveNodeAsTemplate;
import neptune.web.server.operations.StartNode;

/**
 * @author Roberto Bifulco [RobertoBifulco.it] [info@robertoBifulco.it]
 *
 */
public class NodeOpsPH implements PermissionHandler {

	/* (non-Javadoc)
	 * @see it.robertobifulco.ias.PermissionHandler#verifyPermission(java.lang.String, it.robertobifulco.ias.principalmanager.Principal)
	 */
	public void verifyPermission(String operationName, Principal principal)
			throws UnauthorizedOperationException {
		if (operationName.equals(PauseNode.ID) ||
				operationName.equals(RebootNode.ID) ||
				operationName.equals(StartNode.ID) ||
				operationName.equals(SaveNodeAsTemplate.ID)){
//			Il system admin ha diritto di cancellare qualsiasi esperimento
			if(principal.getRole().equals(DefaultRoles.SYSTEM_ADMIN))
				return;
			
			throw new UnauthorizedOperationException(
					"Not enough infos to concede the permission");
		}
	}

	/* (non-Javadoc)
	 * @see it.robertobifulco.ias.PermissionHandler#verifyPermission(java.lang.String, it.robertobifulco.ias.principalmanager.Principal, java.lang.Object)
	 */
	public void verifyPermission(String operationName, Principal principal,
			Object extraInfos) throws UnauthorizedOperationException {
		if (!(operationName.equals(PauseNode.ID) ||
				operationName.equals(RebootNode.ID) ||
				operationName.equals(StartNode.ID) ||
				operationName.equals(SaveNodeAsTemplate.ID)))
			return;

//		Il system admin ha diritto di cancellare qualsiasi esperimento
		if(principal.getRole().equals(DefaultRoles.SYSTEM_ADMIN))
			return;		
		
		String experimentId = (String) extraInfos;
		try {
			String expAdmin = ApplicationManager.getApplicationManager()
					.getNeptuneManager().getExperimentsRepository()
					.getExperimentAdmin(experimentId);

			if (expAdmin.equals(principal.getId()))
				return;

		} catch (ExperimentRepositoryException e) {
			throw new UnauthorizedOperationException(e);
		} catch (InitializationException e) {
			e.printStackTrace();
			throw new UnauthorizedOperationException(e);
		}

		throw new UnauthorizedOperationException("Operation " + operationName
				+ " is unauthorized for principal " + principal.getId());
	}

}
